﻿using AbpVnext_Module.Dto;
using AutoMapper.Internal.Mappers;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.Application.Dtos;
using Volo.Abp.Application.Services;
using Volo.Abp.Authorization.Permissions;
using Volo.Abp.DependencyInjection;
using Volo.Abp.Uow;
using youzackcom.ISeivice;
using youzackcom.Repository;
using youzackcom.Model;

namespace youzackcom.Service
{
    [Dependency(ServiceLifetime.Transient)]
    public class PermissionService : CrudAppService<
                                      Permission,
                                      PermissionDto,
                                      PermissionPageResultDto,  //获取列表返回参数dto
                                      int, //主键
                                      PermissionPageDto, //查询入参
                                      PermissionCreateDto, //创建入参dto
                                      PermissionUpdateDto>  //更新入参dto
                                     , IPermissionService
    {
        public PermissionService(IPermissionRepository permissionRepository) : base(permissionRepository)
        {

        }

        //权限定义管理者
        public PermissionDefinitionManager permissionDefinitionManager { get; set; }

        /// <summary>
        /// 属性医药
        /// </summary>
        public IPermissionRepository permissionRepository { get; set; }

        //protected IReadOnlyList<IPermissionManagementProvider> ManagementProviders => _lazyProviders.Value;

        //public Lazy<List<IPermissionManagementProvider>> _lazyProviders;

        //public IOrderService orderService { get; set; }

        public IObjectMapper _ObjectMapper { get; set; }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public override async Task<PagedResultDto<PermissionPageResultDto>> GetListAsync(PermissionPageDto input)
        {
            return await base.GetListAsync(input);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public override async Task<PermissionDto> GetAsync(int id)
        {
            //return base.GetAsync(id);
            return await base.GetAsync(id);
        }

        /// <summary>
        /// 自定义方法
        /// </summary>
        public void CustomeLog()
        {

        }





        //[LogEnable]   //动态代理 拦截器(aop)
        /// <summary>
        /// 测试事务
        /// </summary>
        /// <returns></returns>
        public async Task<string> CreatePerMange()
        {
            using (var uow = UnitOfWorkManager.Begin())
            {
                //ProductImageDto productImageDto = new ProductImageDto();
                //try
                //{
                //    //await CurrentUnitOfWork.SaveChangesAsync();
                //    await permissiontMannage.CreatePerMange(new PermissionProduct());
                //    //执行任务【工作单元】 提交任务 
                //    await uow.CompleteAsync();
                //}
                //catch (Exception ex)
                //{
                //    await uow.RollbackAsync();
                //}
                return "xxx";
            }

            #region 动态代理（拦截器），不拦截自定义方法
            {
                //var tt = await productImageRepository.GetQueryableAsync();
                //var xx = from it in tt
                //         join ix in tt
                //         on it.Id equals ix.Id  
                //         where  it.Id != null
                //         select it;

                //var xxs = xx.ToList();
                //var xxCount = xx.Count();

                //var xw = tt.Join(tt, x => x.Id, y => y.Id, (x, y) => new
                //{
                //    i = x,
                //    ii = y
                //}).Select(x => new
                //{
                //     id = x.i.Id,
                //     name = x.i.Url,
                //     isd = x.ii.Id,
                //     names = x.ii.Url
                //});

                //var xws = xw.ToList();
                //var xwsCount = xws.Count();
                //var uow = UnitOfWorkManager.Begin();
                //CustomeLog();

                //动态代理会拦截框架内的增删改查方法
                //ProductImageDto productImageDto = new ProductImageDto();
                //var productImage1 = await base.CreateAsync(input);
                //return productImageDto;
            }
            #endregion
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        //[LogEnable]   //动态代理 拦截器(aop)
        //[AllowAnonymous]   //域名匿名访问,过滤鉴权拦截
        //[UnitOfWork]
        public override async Task<PermissionDto> CreateAsync(PermissionCreateDto input)
        {
            //return await base.CreateAsync(input);
            //将权限定义存储到数据库中
            var permission = await permissionDefinitionManager.GetOrNullAsync("Product_Delete");
            IReadOnlyList<PermissionGroupDefinition> groupDefinitions = await permissionDefinitionManager.GetGroupsAsync();
            foreach (var item in groupDefinitions)
            {
                IReadOnlyList<PermissionDefinition> permissionDefinitions = item.Permissions;
                foreach (var it in permissionDefinitions)
                {
                    Permission permissionProduct = new Permission();
                    permissionProduct.PermissionName = it.Name;
                    permissionProduct.PermissionGroup = item.Name;
                    permissionProduct.ParentPermissionName = "";
                    //添加数据
                    await Repository.InsertAsync(permissionProduct);
                    var chauild = it.Children;
                    if (chauild != null && chauild.Count > 0)
                        await AddPermissionDefinition(it, it.Name, item.Name);
                }
            }
            return new PermissionDto();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="permissionDefinition"></param>
        /// <param name="ParentPermissionName"></param>
        /// <param name="PermissionGroup"></param>
        /// <returns></returns>
        public async Task AddPermissionDefinition(PermissionDefinition permissionDefinition, string ParentPermissionName, string PermissionGroup)
        {
            var chauild = permissionDefinition.Children;
            foreach (var item in chauild)
            {
                Permission permissionProduct = new Permission();
                permissionProduct.PermissionName = item.Name;
                permissionProduct.PermissionGroup = PermissionGroup;
                permissionProduct.ParentPermissionName = ParentPermissionName;
                //添加数据
                await Repository.InsertAsync(permissionProduct);
                var cha = item.Children;
                if (cha != null && cha.Count > 0)
                    await AddPermissionDefinition(item, item.Name, PermissionGroup);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="id"></param>
        /// <param name="input"></param>
        /// <returns></returns>
        public override async Task<PermissionDto> UpdateAsync(int id, PermissionUpdateDto input)
        {
            return await base.UpdateAsync(id, input);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public override async Task DeleteAsync(int id)
        {
            await Repository.DeleteAsync(id);
        }
    }
}
